package com.example.bindservice;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    private MyService.MyBinder myBinder;
    private MyConn myconn;
    private Button btn_bind, btn_call, btn_unbind;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        btn_bind = (Button) findViewById(R.id.btn_bind);
        btn_call = (Button) findViewById(R.id.btn_call);
        btn_unbind = (Button) findViewById(R.id.btn_unbind);
        btn_unbind.setOnClickListener(this);
        btn_bind.setOnClickListener(this);
        btn_call.setOnClickListener(this);
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_bind:
                if (myconn == null) {
                    myconn = new MyConn();
                }
                Intent intent = new Intent(MainActivity.this, MyService.class);
                bindService(intent, myconn, BIND_AUTO_CREATE);
                break;
            case R.id.btn_call:
                if (myBinder == null) return;
                myBinder.callMethodInService();
                break;
            case R.id.btn_unbind:
                if (myconn != null) {
                    unbindService(myconn);
                    myconn = null;
                    myBinder = null;
                }
                break;
        }
    }

    private class MyConn implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            myBinder = (MyService.MyBinder) iBinder;
            Log.i("MainActivity", "服务绑定成功, 地址为: " + myBinder.toString());
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
        }
    }
}